package net.neptech.controller;

import com.alibaba.fastjson2.JSON;
import lombok.RequiredArgsConstructor;
import net.neptech.entity.SpeechText;
import net.neptech.entity.vo.dto.KSignalMessage;
import net.neptech.service.ai.AiSummaryService;
import net.neptech.utils.StringUtils;
import net.neptech.websocket.SignalingWebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.List;

@RestController
@RequestMapping("/ai")
@RequiredArgsConstructor
public class AiSummaryController {
    private final RedisTemplate<String, Object> redisTemplate;
    private final AiSummaryService aiSummaryService;
    private final KafkaTemplate<String, String> kafkaTemplate; // 👈 注入 Kafka

    @GetMapping("/summary/{conferenceId}")
    public ResponseEntity<String> generateSummary(@PathVariable String conferenceId) {
        String cacheKey = "meeting:summary:" + conferenceId;
        String cached = (String) redisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.hasText(cached)) {
            return ResponseEntity.ok(cached);
        }

        // 拉逐字稿 + 文件
        var trObjs = redisTemplate.opsForList().range("meeting:transcripts:" + conferenceId, 0, -1);
        var transcripts = (trObjs == null ? List.<SpeechText>of() : trObjs.stream().map(o -> (SpeechText) o).toList());
        var fileObjs = redisTemplate.opsForList().range("meeting:files:" + conferenceId, 0, -1);
        var files = (fileObjs == null ? List.<String>of() : fileObjs.stream().map(Object::toString).toList());

        // 调 AI
        String summary = aiSummaryService.generateMeetingSummary(conferenceId, transcripts, files);

        // 存 7 天
        redisTemplate.opsForValue().set(cacheKey, summary, Duration.ofDays(7));

        // ✅ 改成发 Kafka，而不是本地 broadcast
        KSignalMessage kMsg = new KSignalMessage();
        kMsg.setConferenceId(conferenceId);
        kMsg.setFromUserId("system");   // 或者触发医生的 ID
        kMsg.setType("ai-meeting-summary");
        kMsg.setData(summary);

        kafkaTemplate.send("lxy-signaling-top", JSON.toJSONString(kMsg));

        return ResponseEntity.ok(summary);
    }
}

